import request from "@http/request";
import {
  Toast
} from 'antd-mobile'

const apis = {
  // 获取验证码
  getCaptchas() {
    const error = '机器人服务初始化失败'

    return request({
      url: '/maap/passport/enterprise/captchas',
      method: 'get',
    }).then(res => {
      return res
    }).catch((err) => {
      Toast.info(error, 1, null, false)
      throw err
    })
  },

  // 获取指定机器人信息
  getChatBotInfo(info = {
    merchantId: '',
    chatbotId: ''
  }) {
    const error = '获取机器人信息失败'

    return request({
      url: '/maap/chatbot/chatbot/get',
      method: 'post',
      params: info
    }).then(res => {
      if (res.status === 200 && res.data.code === 200 && res.data.status !== 2) {
        return res
      } else {
        throw error
      }
    }).catch((err) => {
      Toast.info(error, 1, null, false)
      throw err
    })
  },

  // 检查机器人连接状态
  getConnection(info = {
    merchantId: '',
    chatbotId: ''
  }) {
    const error = <div>未知错误<br />没有找到该机器人服务</div>
    const success = '连接成功'

    return Promise.all([
      this.getCaptchas(),
      this.getChatBotInfo(info)
    ]).then(resArr => {
      const res = resArr.every((item) => !!item)

      if (!res) {
        Toast.info(error, 1, null, false)
        throw error
      } else {
        Toast.info(success, 1, null, false)
        return true
      }
    }).catch(err => {
      Toast.info(error, 1, null, false)
      throw err
    })
  },

  // 发送消息
  sendMessage(info = {
    merchant_id: '',
    chatbot_id: '',
    session_id: '',
    text: ''
  }) {
    const error = <div>发送失败<br />该机器人服务错误</div>

    return request({
      url: '/maap/chatbot/message/send',
      method: 'post',
      params: info
    }).then(res => {
      console.log(res)
      if (res.data.code === 200 && res.data.data) {
        return res
      } else {
        throw error
      }
    }).catch((err) => {
      Toast.info(error, 1, null, false)
      throw err
    })
  },

  getApplicationInfo(id){
    const error = '获取应用信息失败'

    return request({
      url: `/maap/messenger/enterprise/applications/${id}`,
      method: 'get',
    }).then(res => {
      if (res.status === 200) {
        return res
      } else {
        throw error
      }
    }).catch((err) => {
      Toast.info(error, 1, null, false)
      throw err
    })
  }

}


export default apis